package com.toptech.testapp;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    /*************************************************/
    private static final int EVENT_SENSOR = 0x0;
    private AudioManager mAudioManager;
    private HandlerThread thread;
    private EventHandler mHandler;

    class EventHandler extends Handler{

        public EventHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case EVENT_SENSOR:
                    removeMessages(EVENT_SENSOR);

                    sendEmptyMessageDelayed(EVENT_SENSOR,100);
                    break;
            }
        }
    }

    public static boolean checkRootPathSU() {
        File f = null;
        final String[] kSuSearchPaths = {"/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/"};
        try {
            for (int i = 0; i < kSuSearchPaths.length; i++) {
                f = new File(kSuSearchPaths[i] + "su");
                if (f != null && f.exists()) {
                    Log.i(TAG, "find su in : " + kSuSearchPaths[i]);
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean checkRootWhichSU() {
        String[] strCmd = new String[]{"/system/bin/which", "su"};
        ArrayList<String> execResult = executeCommand(strCmd);
        if (execResult != null) {
            Log.i(TAG, "execResult=" + execResult.toString());
            return true;
        } else {
            Log.i(TAG, "execResult=null");
            return false;
        }
    }

    public static ArrayList<String> executeCommand(String[] shellCmd) {
        String line = null;
        ArrayList<String> fullResponse = new ArrayList<String>();
        Process localProcess = null;
        try {
            Log.i(TAG, "to shell exec which for find su :");
            localProcess = Runtime.getRuntime().exec(shellCmd);
        } catch (Exception e) {
            return null;
        }
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(localProcess.getOutputStream()));
        BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));
        try {
            while ((line = in.readLine()) != null) {
                Log.i(TAG, "–> Line received: " + line);
                fullResponse.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i(TAG, "–> Full response was: " + fullResponse);
        return fullResponse;
    }

    public static synchronized boolean checkGetRootAuth() {
        Process process = null;
        DataOutputStream os = null;
        try {
            Log.i(TAG, "to exec su");
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes("exit\n");
            os.flush();
            int exitValue = process.waitFor();
            Log.i(TAG, "exitValue=" + exitValue);
            BufferedReader bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            BufferedReader bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));

            String line = null;
            if(exitValue != 1){
                Log.d(TAG, "checkGetRootAuth info : ");
                while ((line = bufrIn.readLine()) != null) {
                    Log.d(TAG, "checkGetRootAuth info : " +line);
                }

                Log.e(TAG, "checkGetRootAuth Error : ");
                while ((line = bufrError.readLine()) != null) {
                    Log.e(TAG, "checkGetRootAuth Error : "+line);
                }
            }
            return exitValue == 0;
        } catch (Exception e) {
            Log.i(TAG, "Unexpected error - Here is what I know: "
                    + e.getMessage());
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static synchronized boolean checkBusybox() {
        try {
            Log.i(TAG, "to exec busybox df");
            String[] strCmd = new String[]{"busybox", "df"};
            ArrayList<String> execResult = executeCommand(strCmd);
            if (execResult != null) {
                Log.i(TAG, "execResult=" + execResult.toString());
                return true;
            } else {
                Log.i(TAG, "execResult=null");
                return false;
            }
        } catch (Exception e) {
            Log.i(TAG, "Unexpected error - Here is what I know: "
                    + e.getMessage());
            return false;
        }
    }

    public boolean checkSystemRoot(){
        File f = null;
        final String kSuSearchPaths[] = { "/system/bin/", "/system/xbin/",
                "/system/sbin/", "/sbin/", "/vendor/bin/" };
        try {
            for (int i = 0; i < kSuSearchPaths.length; i++) {
                f = new File(kSuSearchPaths[i] + "su");
                if (f != null && f.exists()&&f.canExecute()) {
                    return true;
                }
            }
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAudioManager = (AudioManager)this.getSystemService(AUDIO_SERVICE);
        //if (checkDeviceDebuggable()){return true;}//check buildTags
        //if (checkSuperuserApk()){return true;}//Superuser.apk
        if (checkRootPathSU()) {
            ((TextView)findViewById(R.id.checkRootPathSU_value)).setText("Success");

        }//find su in some path
        if (checkRootWhichSU()) {
            ((TextView)findViewById(R.id.RootWhichSU_value)).setText("Success");
        }//find su use 'which'
        if (checkBusybox()) {
            ((TextView)findViewById(R.id.checkBusybox_value)).setText("Success");
        }//find su use 'which'
        //exec su
        if(checkGetRootAuth()){
            ((TextView)findViewById(R.id.checkGetRootAuth_value)).setText("Success");
        }

        if(checkSystemRoot()){
            ((TextView)findViewById(R.id.checkSystemRoot_value)).setText("Success");
        }
        thread = new HandlerThread("MessThread");
        thread.start();
        mHandler = new EventHandler(thread.getLooper());
        mHandler.sendEmptyMessage(EVENT_SENSOR);

        features.setKeyFeature(this.getWindow(),true);
    }

    private  KeyFeatures features = new KeyFeatures();
    @Override
    protected void onResume() {
        super.onResume();
        mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);//add by song
        sendMediaKeyCode(this,KeyEvent.KEYCODE_MEDIA_PAUSE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_0:
                break;
            case KeyEvent.KEYCODE_1:

                features.setKeyFeature(this.getWindow(),false);
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_VOLUME_MUTE:
                Log.d(TAG,"[hangup] keycode = "+keyCode);
                Toast.makeText(this,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaa",Toast.LENGTH_LONG).show();
                return true;

        }
        return super.onKeyDown(keyCode, event);
    }

    private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
        }
    };

    public static void sendMediaKeyCode(Context context, int keyCode) {
        AudioManager audioManager= (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager.isMusicActive()){
            KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
            Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
            context.sendOrderedBroadcast(intent,null);

            keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
            intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
            context.sendOrderedBroadcast(intent,null);
        }
    }

}
